<?php
class EnumsController extends BaseManageController{
	public function actionAdmin(){
		$this->pageTitle = '枚举管理列表 - ' . Yii::app()->name;
		$mod = new EnumsModel();
		$con = array(
			'site_id' => SITE_ID
		);
		$total = $mod->count($con);
		$this->setPagination($total);
		$enums_list = $mod->find($con, null, $this->pager->offset, $this->pager->pageSize);
		$this->render('admin', array('list'=>$enums_list));
	}
	
	public function actionEdit($id = null){
		if(Yii::app()->request->isPostRequest){
			$this->_save($id);
		}
		if($id == null){
			$enum = array(
				'_id' => '',
			);
		}else{
			$enum = EnumsModel::model()->get_by_key($id);
			if($enum['site_id'] != SITE_ID){
				throw new CHttpException(403, '非法请求！');
			}
		}
		$this->pageTitle = '枚举类型编辑 - ' . Yii::app()->name;
		$this->render('edit', array('model'=>$enum));
	}
	
	private function _save($id = null){
		$enum = $_POST['Enum'];
		$enum_values = $_POST['EnumValues'];
		$enum_names = $_POST['EnumNames'];
		$values = array();
		foreach ($enum_values as $index=>$val){
			if(in_array($val, $values)){
				$this->ajax_error('枚举值不能重复！');
			}
			$enum['items'][$index] = $enum_names[$index];
		}
		
		$mod = new EnumsModel();
		
		$con = array('site_id'=>SITE_ID);
		if(empty($enum['_id'])){
			$con['code'] = $enum['code'];
		}else{
			$con['code'] = $enum['code'];
			$con['_id'] = array('neq'=>$enum['_id']);
		}
		
		if($mod->exists_attrs($con)){
			$this->ajax_error('枚举编码已经存在！');
		}
		
		if(empty($enum['_id'])){
			//新建
			$enum['site_id'] = SITE_ID;
			unset($enum['_id']);
			$mod->insert($enum);
		}else{
			$mod->update_by_key($enum['_id'], $enum);
		}
		$this->ajax_info('保存成功！', $enum);
	}
}

?>